<template>
  <el-row>
    <el-card>
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item :label="tableText['orderCreateTime']">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="tableText['productType']">
          <el-select v-model="searchForm.loanProductType" multiple collapse-tags clearable :placeholder="$t('letterReviewOrder.prompt.productType')" style="width: 300px">
            <el-option
              v-for="item in tableText['productTypes']"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.limit')">
          <el-row>
            <el-col :span="13">
              <el-select v-model="searchForm.loanDaysFlag" clearable :placeholder="$t('common.select')">
                <el-option
                  v-for="item in $t('financeModule.list.operatorData')"
                  :key="item.value"
                  :label="item.desc"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="11">
              <el-input v-model="searchForm.loanDays" clearable type="number" :placeholder="$t('financeModule.list.days')" :maxlength="50" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.reBorrow')">
          <el-select v-model="searchForm.firstLoan">
            <el-option
              v-for="item in $t('financeModule.list.borrowData')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="tableText['orderStatus']">
          <el-select v-model="searchForm.creditOrderStatus" multiple collapse-tags clearable :placeholder="$t('letterReviewOrder.prompt.orderStatus')" style="width: 300px">
            <el-option
              v-for="item in stageData"
              :key="item.id"
              :label="item.flowName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="tableText['reviewOrderNo']">
          <el-input v-model="searchForm.creditOrderNo" clearable :placeholder="$t('letterReviewOrder.prompt.reviewOrderNo')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="tableText['phoneNumber']">
          <el-input v-model="searchForm.userPhone" type="tel" clearable :placeholder="$t('letterReviewOrder.prompt.phoneNumber')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="tableText['letterReviewer']">
          <el-input v-model="searchForm.currentAuditStaffName" clearable :placeholder="$t('letterReviewOrder.prompt.letterReviewer')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('usrModule.list.table.channelSource')">
          <el-select v-model="searchForm.channel" clearable :placeholder="$t('usrModule.list.prompt.channelSource')" @change="setSource">
            <el-option
              v-for="item in $t('usrModule.list.source')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('usrModule.list.table.promotionMethod')">
          <el-select v-model="searchForm.promotionTypeStr" clearable multiple collapse-tags :placeholder="$t('usrModule.list.prompt.promotionMethod')">
            <el-option
              v-for="item in promotionData"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('usrModule.list.table.referrer')">
          <el-input v-model="searchForm.referrerName" clearable :placeholder="$t('usrModule.list.prompt.referrer')" :maxlength="50" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
          <el-button :disabled="!(totalNumber > 0)" @click="exportList">
            {{ $t('common.ex') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-row>
        <el-button :disabled="multipleSelection.length === 0" type="primary" @click="allocation">
          {{ tableText['distribution'] }}<span v-if="multipleSelection.length > 0">（{{ multipleSelection.length }}）</span>
        </el-button>
        <el-button :disabled="multipleSelection.length === 0" type="primary" @click="operating(1)">
          {{ tableText['shutDown'] }}<span v-if="multipleSelection.length > 0">（{{ multipleSelection.length }}）</span>
        </el-button>
        <el-button :disabled="multipleSelection.length === 0" type="primary" @click="operating(2)">
          {{ tableText['refuse'] }}<span v-if="multipleSelection.length > 0">（{{ multipleSelection.length }}）</span>
        </el-button>
        <el-button :disabled="multipleSelection.length === 0" type="primary" @click="operating(3)">
          {{ tableText['goBack'] }}<span v-if="multipleSelection.length > 0">（{{ multipleSelection.length }}）</span>
        </el-button>
      </el-row>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        tooltip-effect="dark"
        :stripe="true"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          fixed="left"
          type="selection"
          width="55"
          :selectable="selectable"
        />
        <el-table-column
          fixed="left"
          prop="creditOrderNo"
          :label="tableText['reviewOrderNo']"
          min-width="170"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="auth(scope.row)">
              {{ scope.row.creditOrderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          fixed="left"
          prop="creditOrderOperate"
          :label="tableText['orderCreateTime']"
          min-width="170"
        >
          <template slot-scope="scope">
            {{ scope.row['createTimeStr'] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="userPhone"
          :label="tableText['phoneNumber']"
          min-width="150"
        />
        <el-table-column
          prop="userGrade"
          :label="tableText['userLevel']"
          min-width="100"
        />
        <el-table-column
          prop="channelStr"
          :label="$t('usrModule.list.table.channelSource')"
          min-width="100"
        />
        <el-table-column
          prop="promotionTypeStr"
          :label="$t('usrModule.list.table.promotionMethod')"
          min-width="100"
        />
        <el-table-column
          prop="referrerName"
          :label="$t('usrModule.list.table.referrer')"
          min-width="100"
        />
        <el-table-column
          prop="loanProductType"
          :label="tableText['productType']"
          min-width="220"
        >
          <template slot-scope="scope">
            {{ setType(scope.row['loanProductType']) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="applyMonth"
          :label="tableText['periodsNumber']"
          min-width="120"
        />
        <el-table-column
          prop="applyMoney"
          :label="tableText['loanAmount']"
          min-width="120"
        />
        <el-table-column
          prop="loanDays"
          :label="tableText['loanPeriod']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ (scope.row['loanDays'] && scope.row['applyMonth']) ? (scope.row['loanDays'] * scope.row['applyMonth']) : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="currentAuditStaffName"
          :label="tableText['letterReviewer']"
          min-width="120"
        />
        <el-table-column
          fixed="right"
          prop="currentStageName"
          :label="tableText['orderStatus']"
          min-width="120"
        />
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="200"
        >
          <template slot-scope="scope">
            <el-button size="small" @click="initLetterRecordData(scope.row)">{{ tableText['letterRecord'] }}</el-button>
            <el-button size="small" @click="initCirculationRecordData(scope.row)">{{ tableText['circulationRecord'] }}</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <allocation-dialog
      :show-dialog="allocationDialog"
      :all-staff="allStaff"
      :credit-order-ids="creditOrderIds"
      @change-dialog="changeDialog"
      @edit-success="editSuccess"
    />
    <letter-review-record
      ref="reviewRecord"
      :show-dialog="reviewDialog"
      @change-dialog="changeReview"
    />
    <circulation-record
      ref="circulationRecord"
      :show-dialog="circulationDialog"
      @change-dialog="changeCirculation"
    />
    <operate-dialog
      :show-dialog="operateDialog"
      :credit-order-ids="creditOrderIds"
      :reject-desc-data="rejectDescData"
      :operate-type="operateType"
      @change-dialog="changeOperateDialog"
      @edit-success="editSuccess"
    />
  </el-row>
</template>

<script>
import { getCreditAuditData, exportCreditOrder, listAuditStage, getReview, listAuditRejectDesc, getCreditOrderAllocationStaffList, queryAuditRejectDesc } from '@/api/risk'
import { allPackage } from '@/api/user'
import { formatDate, ObjToQueryString } from '@/utils/method'
import LetterReviewRecord from '@/components/risk/riskManagement/letter-review-record'
import CirculationRecord from '@/components/risk/riskManagement/circulation-record'
import AllocationDialog from '@/components/risk/riskManagement/allocation-dialog'
import OperateDialog from '@/components/risk/riskManagement/operate-dialog'
export default {
  name: 'LetterReviewOrder',
  components: {
    LetterReviewRecord,
    CirculationRecord,
    AllocationDialog,
    OperateDialog
  },
  data() {
    return {
      allStaff: [],
      loading: true,
      allocationDialog: false,
      operateDialog: false,
      reviewDialog: false,
      circulationDialog: false,
      letterRecordLoading: false,
      tableData: [],
      time: '',
      tableText: {},
      totalNumber: 0,
      stageData: [],
      allStage: [],
      letterRecordData: [],
      orderNo: null,
      promotionData: [],
      allPackageData: [],
      rejectDescData: [],
      listAuditRejectDescData: [],
      searchForm: this.params(),
      creditOrderIds: [],
      multipleSelection: [],
      operateType: null,
      operatingTip: null,
      operatingTitle: null
    }
  },
  mounted() {
    this.time = [new Date(), new Date()]
    this.tableText = this.$t('letterReviewOrder')
    this.getStageData()
    this.getAllStage()
    // this.getRejectDescData()
    this.getAllPackage()
    setTimeout(() => {
      this.getData()
    }, 10)
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        applyDateBegin: null,
        applyDateEnd: null,
        userGrade: null,
        loanProductType: ['1', '2', '3', '4'],
        creditOrderStatus: null,
        auditRejectStageId: null,
        rejectId: [],
        creditOrderNo: null,
        userPhone: null,
        currentAuditStaffName: null,
        loanDaysFlag: null,
        loanDays: null,
        channel: null,
        promotionTypeStr: null,
        referrerName: null,
        firstLoan: ''
      }
    },
    initLetterRecordData(data) {
      this.reviewDialog = true
      setTimeout(() => {
        this.$refs.reviewRecord.getData(data.id)
      }, 10)
    },
    initCirculationRecordData(data) {
      this.circulationDialog = true
      setTimeout(() => {
        this.$refs.circulationRecord.getData(data.id)
      }, 10)
    },
    selectable(row) {
      return row['status'] === 9
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getAllPackage() {
      allPackage()
        .then(res => {
          if (res.success) {
            this.allPackageData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getStageData() {
      listAuditStage()
        .then(res => {
          if (res.success) {
            this.stageData = res.data.filter(v => {
              return v['flowName'] !== null
            })
            this.searchForm.creditOrderStatus = []
            this.stageData.forEach(v => {
              this.searchForm.creditOrderStatus.push(v['id'])
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getAllStage() {
      const data = {
        isPage: false
      }
      getReview(data)
        .then(res => {
          if (res.success) {
            this.allStage = res.data
            this.searchForm.auditRejectStageId = []
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getRejectDescData() {
      listAuditRejectDesc()
        .then(res => {
          if (res.success) {
            this.listAuditRejectDescData = res.data
            this.searchForm.rejectId = []
            this.listAuditRejectDescData.forEach(v => {
              this.searchForm.rejectId.push(JSON.stringify(v))
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.searchForm = this.params()
      this.searchForm.creditOrderStatus = []
      this.stageData.forEach(v => {
        this.searchForm.creditOrderStatus.push(v['id'])
      })
      this.time = [new Date(), new Date()]
      this.getData()
    },
    setType(data) {
      const name = this.tableText['productTypes'].filter(item => {
        return item.value === data
      })
      return (name && name[0] && name[0].desc) ? name[0].desc : ''
    },
    textDesc(data) {
      if (data) {
        const str = JSON.parse(JSON.stringify(data)).join('<br/><br/>')
        return str
      }
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    searchData() {
      const data = {
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize,
        userGrade: this.searchForm.userGrade,
        loanProductType: this.searchForm.loanProductType,
        auditRejectStageId: this.searchForm.auditRejectStageId,
        creditOrderNo: this.searchForm.creditOrderNo,
        userPhone: this.searchForm.userPhone,
        currentAuditStaffName: this.searchForm.currentAuditStaffName,
        loanDaysFlag: this.searchForm.loanDaysFlag,
        loanDays: this.searchForm.loanDays,
        channel: this.searchForm.channel,
        promotionTypeStr: this.searchForm.promotionTypeStr,
        referrerName: this.searchForm.referrerName,
        firstLoan: this.searchForm.firstLoan,
        columns: ['order_create_time'],
        orderBy: [false]
      }
      if (this.time && this.time.length > 1) {
        data['applyDateBegin'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['applyDateEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['applyDateBegin'] = null
        data['applyDateEnd'] = null
      }
      if (this.searchForm.creditOrderStatus.length === this.stageData.length) {
        data['creditOrderStatus'] = []
      } else {
        data['creditOrderStatus'] = this.searchForm.creditOrderStatus
      }
      return data
    },
    getData() {
      this.loading = true
      getCreditAuditData(this.searchData())
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    exportList() {
      exportCreditOrder(this.searchData())
    },
    setSource() {
      const channel = this.searchForm.channel
      if (channel === 1) {
        this.promotionData = this.$t('usrModule.list.method')
      } else if (channel === 2) {
        this.promotionData = this.$t('usrModule.list.method1')
      } else if (channel === 3) {
        this.promotionData = []
        const arr = this.allPackageData.filter(v => {
          return v['mediaSource'] !== null
        })
        const node = []
        arr.forEach(v => {
          node.push({
            desc: v['mediaSource'],
            value: v['mediaSource']
          })
        })
        this.promotionData = node
      } else {
        this.promotionData = []
      }
      this.searchForm.promotionTypeStr = null
    },
    allocation() {
      if (this.multipleSelection.length > 0) {
        this.creditOrderIds = []
        this.multipleSelection.forEach(v => {
          this.creditOrderIds.push(v.id)
        })
        this.loading = true
        const data = {
          creditOrderList: this.creditOrderIds
        }
        getCreditOrderAllocationStaffList(data)
          .then(res => {
            this.loading = false
            if (res.success) {
              const arr = res.data
              if (arr && arr.length === 0) {
                this.$message.error(this.$t('letterReviewOrder.commissionerNo'))
                return
              }
              const option = []
              arr.forEach(item => {
                if (!option.includes(item['firmName'])) {
                  option.push(item['firmName'])
                }
              })
              const optionData = []
              option.forEach((v, i) => {
                const children = []
                const a = arr.filter(item => {
                  return item['firmName'] === v
                })
                const arr1 = []
                a.forEach(item => {
                  if (!arr1.includes(item['groupName'])) {
                    arr1.push(item['groupName'])
                  }
                })
                arr1.forEach((f, index) => {
                  const b = a.filter(item => {
                    return item['groupName'] === f
                  })
                  const grand = []
                  b.forEach(grandson => {
                    grand.push({
                      label: grandson['staffName'] + '----' + grandson['currentOrderNum'],
                      value: grandson['id']
                    })
                  })
                  children.push(
                    {
                      label: f,
                      value: `groupName${index}`,
                      children: grand
                    }
                  )
                })
                optionData.push({
                  label: v,
                  value: i,
                  children: children
                })
              })
              this.allStaff = optionData
              this.allocationDialog = true
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(err => {
            this.loading = false
            this.$message.error(err.message)
          })
      }
    },
    operating(data) {
      if (this.multipleSelection.length > 0) {
        this.creditOrderIds = []
        this.multipleSelection.forEach(v => {
          this.creditOrderIds.push(v.id)
        })
        this.operateType = data
        if (data === 1) {
          this.loading = true
          queryAuditRejectDesc()
            .then(res => {
              this.loading = false
              if (res.success) {
                this.rejectDescData = res.data
                this.operateDialog = true
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error(err.message)
            })
        } else {
          this.operateDialog = true
        }
      }
    },
    changeDialog(param) {
      this.allocationDialog = param
    },
    changeOperateDialog(param) {
      this.operateDialog = param
    },
    editSuccess() {
      this.getData()
    },
    changeReview(data) {
      this.reviewDialog = data
    },
    changeCirculation(data) {
      this.circulationDialog = data
    },
    auth(item) {
      const paramData = {
        from: 'auditedList',
        status: item['status'],
        userId: item['userId'],
        orderId: item['id'],
        orderNo: item['creditOrderNo']
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/usr/auth?${para}`, '_blank')
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
.el-table{
  margin-top: 10px;
}
</style>
